
// 模板类
const Template = {
    // 初始化模板
    init(id) {
        try {
            let vTemplate = $("#" + id);
            let arySelect = new Array();
            let aryDate = new Array();
            let vHtml = "";

            for (let i = 0; i < vTemplate[0].content.children.length; i++) {

                //console.log(vTemplate[0].content.children[i]);

                let vType = "text";
                let vName = vTemplate[0].content.children[i].attributes["name"].value;
                let vTitle = vTemplate[0].content.children[i].attributes["title"].value;
                let vWidth = "6";
                let vDataType = "datatype=\"C\"";
                let vDisabled = "";
                let vOnBind = "";
                let vReadonly = "";
                let vBind = "";
                let vDisplay = "";
                let vVerifyClass = "";
                let vVerifyID = "";
                let vVerifyControl = "";
                let vVerifyText = "";

                // 获取type属性
                if (vTemplate[0].content.children[i].attributes["type"] != undefined) {
                    vType = vTemplate[0].content.children[i].attributes["type"].value;
                }

                // 获取width属性
                if (vTemplate[0].content.children[i].attributes["width"] != undefined) {
                    vWidth = vTemplate[0].content.children[i].attributes["width"].value;
                }

                // 获取datatype属性
                if (vTemplate[0].content.children[i].attributes["datatype"] != undefined) {
                    vDataType = "datatype=\"" + vTemplate[0].content.children[i].attributes["datatype"].value + "\"";
                }

                // 获取disabled属性
                if (vTemplate[0].content.children[i].attributes["disabled"] != undefined) {
                    vDisabled = "disabled=\"" + vTemplate[0].content.children[i].attributes["disabled"].value + "\"";
                }

                // 获取onbind事件
                if (vTemplate[0].content.children[i].attributes["onbind"] != undefined) {
                    vOnBind = "onbind=\"" + vTemplate[0].content.children[i].attributes["onbind"].value + "\"";
                }

                // 获取readonly属性
                if (vTemplate[0].content.children[i].attributes["readonly"] != undefined) {
                    vReadonly = "readonly=\"" + vTemplate[0].content.children[i].attributes["readonly"].value + "\"";
                }

                // 获取bind属性
                if (vTemplate[0].content.children[i].attributes["bind"] != undefined) {
                    vBind = "bind=\"" + vTemplate[0].content.children[i].attributes["bind"].value + "\"";
                }

                // 获取display属性
                if (vTemplate[0].content.children[i].attributes["display"] != undefined) {
                    vDisplay = "style=\"display:" + vTemplate[0].content.children[i].attributes["display"].value + ";\"";
                }

                // 获取校验是否为空属性
                if (vTemplate[0].content.children[i].attributes["empty"] != undefined) {
                    if (String(vTemplate[0].content.children[i].attributes["empty"].value).toLowerCase() == "true") {
                        vVerifyClass += " " + vTemplate[0].attributes["id"].value + "-verify-" + vTemplate[0].content.children[i].localName + "-empty";
                        vVerifyText += "* ";
                    }
                }

                // 获取校验是否为整数属性
                if (vTemplate[0].content.children[i].attributes["number"] != undefined) {
                    if (String(vTemplate[0].content.children[i].attributes["number"].value).toLowerCase() == "true") {
                        vVerifyClass += " " + vTemplate[0].attributes["id"].value + "-verify-" + vTemplate[0].content.children[i].localName + "-number";
                    }
                }

                // 获取校验是否为数字属性
                if (vTemplate[0].content.children[i].attributes["decimal"] != undefined) {
                    if (String(vTemplate[0].content.children[i].attributes["decimal"].value).toLowerCase() == "true") {
                        vVerifyClass += " " + vTemplate[0].attributes["id"].value + "-verify-" + vTemplate[0].content.children[i].localName + "-decimal";
                    }
                }

                // 获取校验是否为中文属性
                if (vTemplate[0].content.children[i].attributes["chinese"] != undefined) {
                    if (String(vTemplate[0].content.children[i].attributes["chinese"].value).toLowerCase() == "true") {
                        vVerifyClass += " " + vTemplate[0].attributes["id"].value + "-verify-" + vTemplate[0].content.children[i].localName + "-chi";
                    }
                }

                // 获取校验是否为英文属性
                if (vTemplate[0].content.children[i].attributes["english"] != undefined) {
                    if (String(vTemplate[0].content.children[i].attributes["english"].value).toLowerCase() == "true") {
                        vVerifyClass += " " + vTemplate[0].attributes["id"].value + "-verify-" + vTemplate[0].content.children[i].localName + "-eng";
                    }
                }

                // 获取校验名称是否合法属性
                if (vTemplate[0].content.children[i].attributes["current"] != undefined) {
                    if (String(vTemplate[0].content.children[i].attributes["current"].value).toLowerCase() == "true") {
                        vVerifyClass += " " + vTemplate[0].attributes["id"].value + "-verify-" + vTemplate[0].content.children[i].localName + "-cur";
                    }
                }

                // 获取校验是否为电话号码属性
                if (vTemplate[0].content.children[i].attributes["telephone"] != undefined) {
                    if (String(vTemplate[0].content.children[i].attributes["telephone"].value).toLowerCase() == "true") {
                        vVerifyClass += " " + vTemplate[0].attributes["id"].value + "-verify-" + vTemplate[0].content.children[i].localName + "-tel";
                    }
                }

                // 获取校验是否为手机号码属性
                if (vTemplate[0].content.children[i].attributes["email"] != undefined) {
                    if (String(vTemplate[0].content.children[i].attributes["email"].value).toLowerCase() == "true") {
                        vVerifyClass += " " + vTemplate[0].attributes["id"].value + "-verify-" + vTemplate[0].content.children[i].localName + "-email";
                    }
                }

                // 获取校验是否为IP属性
                if (vTemplate[0].content.children[i].attributes["ip"] != undefined) {
                    if (String(vTemplate[0].content.children[i].attributes["ip"].value).toLowerCase() == "true") {
                        vVerifyClass += " " + vTemplate[0].attributes["id"].value + "-verify-" + vTemplate[0].content.children[i].localName + "-ip";
                    }
                }

                // 获取校验是否为日期属性
                if (vTemplate[0].content.children[i].attributes["date"] != undefined) {
                    if (String(vTemplate[0].content.children[i].attributes["date"].value).toLowerCase() == "true") {
                        vVerifyClass += " " + vTemplate[0].attributes["id"].value + "-verify-" + vTemplate[0].content.children[i].localName + "-date";
                    }
                }

                // 设置校验提示文本
                if (vTemplate[0].content.children[i].attributes["verify"] != undefined) {
                    if (String(vTemplate[0].content.children[i].attributes["verify"].value) != "") {
                        vVerifyText += String(vTemplate[0].content.children[i].attributes["verify"].value);
                    }
                }

                if (vVerifyText.length > 0) {
                    if (vType == "date") {
                        vVerifyControl = "<span class=\"spn-warn\">" + vVerifyText + "</span>";
                    }
                    else {
                        vVerifyControl = "<span class=\"input-group-addon spn-warn\">" + vVerifyText + "</span>";
                    }
                }

                // 设置校验控件的ID
                if (vVerifyClass != "") {
                    vVerifyID = "id=\"vrf_" + vName + "\"";
                }

                if (i == 0) {
                    vHtml += `<div class="col-sm-12" style="display:none;">
                        <div class="input-group">
                            <span class="input-group-addon">主键</span>
                            <input id="txt_PK_Value" type="text" class="form-control ${vTemplate[0].attributes["id"].value}" value="" bind="false" />
                        </div>
                        <br />
                    </div>`;
                }

                if (vType == "select") {
                    //下拉列表框
                    let vSearch = "";
                    let vMultiple = "";
                    let vOption = "";



                    if (vTemplate[0].content.children[i].attributes["search"] != undefined) {
                        vSearch = "data-live-search=\"" + vTemplate[0].content.children[i].attributes["search"].value + "\"";
                    }

                    if (vTemplate[0].content.children[i].attributes["multiple"] != undefined) {
                        vMultiple = "multiple=\"" + vTemplate[0].content.children[i].attributes["multiple"].value + "\"";
                    }

                    if (vTemplate[0].content.children[i].attributes["binded"] != undefined) {
                        var vList = eval(vTemplate[0].content.children[i].attributes["binded"].value);

                        for (let j = 0; j < vList.length; j++) {

                            let vKey = "";
                            let vValue = "";

                            if (vList[j]["key"] != null && vList[j]["key"] != undefined) {
                                vKey = vList[j]["key"];
                            }
                            else if (vList[j]["k"] != null && vList[j]["k"] != undefined) {
                                vKey = vList[j]["k"];
                            }

                            if (vList[j]["value"] != null && vList[j]["value"] != undefined) {
                                vValue = vList[j]["value"];
                            }
                            else if (vList[j]["v"] != null && vList[j]["v"] != undefined) {
                                vValue = vList[j]["v"];
                            }

                            if (vList[j]["defaulted"] != undefined && vList[j]["defaulted"] == "true") {
                                vOption += `<option value="` + vKey + `" defaulted="true">` + vValue + `</option>`;
                            }
                            else {
                                vOption += `<option value="` + vKey + `">` + vValue + `</option>`;
                            }
                        }
                    }

                    vHtml += `<div class="col-sm-` + vWidth + `" ` + vDisplay + `>
                        <div class="input-group">
                            <span `+ vVerifyID + ` class="input-group-addon">` + vTitle + `</span>
                            <select id="ddl_`+ vName + `" ` + vDataType + ` ` + vDisabled + ` ` + vOnBind + ` ` + vSearch + ` ` + vMultiple + ` ` + vReadonly + ` ` + vBind + ` class="selectpicker form-control ${vTemplate[0].attributes["id"].value} ` + vVerifyClass + `">
                                `+ vOption + `
                            </select>
                            `+ vVerifyControl + `
                        </div>
                        <br />
                    </div>`;


                    arySelect.push("ddl_" + vName);
                }
                else if (vType == "textarea") {
                    //下拉文本域
                    let vRows = "2";
                    let vFormat = "";

                    if (vTemplate[0].content.children[i].attributes["format"] != undefined) {
                        vFormat = "format=\"" + vTemplate[0].content.children[i].attributes["format"].value + "\"";
                    }

                    if (vTemplate[0].content.children[i].attributes["rows"] != undefined) {
                        vRows = vTemplate[0].content.children[i].attributes["rows"].value;
                    }

                    vHtml += `<div class="col-sm-` + vWidth + `" ` + vDisplay + `>
                        <div class="input-group">
                            <span `+ vVerifyID + ` class="input-group-addon">` + vTitle + `</span>
                            <textarea id="txt_`+ vName + `" type="text" ` + vDataType + ` ` + vDisabled + ` ` + vOnBind + ` ` + vFormat + ` ` + vReadonly + ` ` + vBind + ` class="form-control ${vTemplate[0].attributes["id"].value} ` + vVerifyClass + `" rows="` + vRows + `"></textarea>
                            `+ vVerifyControl + `
                        </div>
                        <br />
                    </div>`;
                }
                else if (vType == "date") {
                    //日期控件
                    let vFormat = "yyyy-MM-dd";
                    let vDays, vMethod, vFirstDay, vEndDay;

                    if (vTemplate[0].content.children[i].attributes["format"] != undefined) {
                        vFormat = vTemplate[0].content.children[i].attributes["format"].value;
                    }

                    if (vTemplate[0].content.children[i].attributes["days"] != undefined) {
                        vDays = Number(vTemplate[0].content.children[i].attributes["days"].value);
                    }

                    if (vTemplate[0].content.children[i].attributes["method"] != undefined) {
                        vMethod = vTemplate[0].content.children[i].attributes["method"].value;
                    }

                    if (vTemplate[0].content.children[i].attributes["firstday"] != undefined) {
                        vFirstDay = vTemplate[0].content.children[i].attributes["firstday"].value;
                    }

                    if (vTemplate[0].content.children[i].attributes["endday"] != undefined) {
                        vEndDay = vTemplate[0].content.children[i].attributes["endday"].value;
                    }

                    vHtml += `<div class="col-sm-` + vWidth + `" ` + vDisplay + `>
                        <div id="div_`+ vName + `" class="input-group date datetimePicker">
                            <span `+ vVerifyID + ` class="input-group-addon">` + vTitle + `</span>
                            <input id="txt_`+ vName + `" type="text" datatype="D" class="form-control ${vTemplate[0].attributes["id"].value}" readonly="readonly" />
                            <span class="input-group-addon">
                                <span class="glyphicon glyphicon-calendar"></span>
                                `+ vVerifyControl + `
                            </span>
                        </div>
                        <br />
                    </div>`;

                    aryDate.push([vName, vFormat, vDays, vMethod, vFirstDay, vEndDay]);
                }
                else {
                    //文本框、密码框
                    let vFormat = "";
                    let vDefaultValue = "sysdate";

                    if (vTemplate[0].content.children[i].attributes["format"] != undefined) {
                        vFormat = "format=\"" + vTemplate[0].content.children[i].attributes["format"].value + "\"";
                    }

                    if (vTemplate[0].content.children[i].attributes["defaultvalue"] != undefined) {
                        vDefaultValue = "defaultvalue=\"" + vTemplate[0].content.children[i].attributes["defaultvalue"].value + "\"";
                    }

                    vHtml += `<div class="col-sm-` + vWidth + `" ` + vDisplay + `>
                        <div class="input-group">
                            <span `+ vVerifyID + ` class="input-group-addon">` + vTitle + `</span>
                            <input id="txt_`+ vName + `" type="` + vType + `" ` + vDataType + ` ` + vDisabled + ` ` + vOnBind + ` ` + vFormat + ` ` + vDefaultValue + ` ` + vReadonly + ` ` + vBind + ` class="form-control ${vTemplate[0].attributes["id"].value} ` + vVerifyClass + `" />
                            `+ vVerifyControl + `
                        </div>
                        <br />
                    </div>`;
                }
            }

            //设置输出域
            var vSpanControl = document.createElement("span");
            vSpanControl.setAttribute("id", "spn_" + id);

            //得到父节点
            var parent = vTemplate[0].parentNode;
            if (parent.lastChild == vTemplate[0]) {
                // 如果最后的节点是目标元素，则直接添加。因为默认是最后
                parent.appendChild(vSpanControl);
            } else {
                //如果不是，则插入在目标元素的下一个兄弟节点 的前面。也就是目标元素的后面
                parent.insertBefore(vSpanControl, vTemplate[0].nextSibling);
            }

            //添加输出域
            vTemplate[0].content.append("<span id=\"spn_" + id + "\"></span>");

            //输出Html
            document.getElementById("spn_" + id).innerHTML = vHtml;

            //初始化日期控件
            for (let i = 0; i < aryDate.length; i++) {

                DateUtil.initDate(aryDate[i][0], aryDate[i][1], aryDate[i][2], aryDate[i][3], aryDate[i][4], aryDate[i][5]);
            }

            //初始化下拉列表控件
            for (let i = 0; i < arySelect.length; i++) {

                $("#" + arySelect[i]).selectpicker('refresh');

            }
        }
        catch (e) {
            alert(e)
        }
    }
}

// 日期工具类
const DateUtil = {
    // 初始化日期控件
    initDate(controlID, format, days, method, firstDay, endDay) {
        try {

            if (days == undefined) {
                days = 0;
            }

            var myDate = new Date();

            var vStartYear = "2011";
            var vStartMonth = "01";
            var vStartDate = "01";

            var vNowYear = myDate.getFullYear();
            var vNowMonth = (myDate.getMonth() + 1) < 10 ? '0' + (myDate.getMonth() + 1) : (myDate.getMonth() + 1);
            var vNowDate = myDate.getDate();

            var vTimeGlobal = "";
            var vStartGlobal = "";
            var vEndGlobal = "";
            var vStartView = 1;

            if (format.toLowerCase() == "yyyy-mm-dd") {
                vStartGlobal = vStartYear + "-" + vStartMonth + "-" + vNowDate
                vEndGlobal = new Date().dateFormat(format);
                if (firstDay) {
                    vTimeGlobal = vNowYear + "-" + vNowMonth + "-" + vStartDate;
                }
                else {
                    var vDate = new Date();
                    vDate.setDate(vDate.getDate() + days);
                    vTimeGlobal = vDate.dateFormat(format);
                }
                vStartView = 2;
            }
            else if (format.toLowerCase() == "yyyy-mm") {
                vStartGlobal = vStartYear + "-" + vStartMonth;
                vEndGlobal = new Date().dateFormat(format);
                vTimeGlobal = new Date().dateFormat(format);
                vStartView = 3;
            }
            else if (format.toLowerCase() == "yyyymm") {
                vStartGlobal = vStartYear + vStartMonth;
                vEndGlobal = new Date().dateFormat(format);
                vTimeGlobal = new Date().dateFormat(format);
                vStartView = 3;
            }

            var vControlDate = $('#div_' + controlID).datetimepicker({
                format: format.toLowerCase(),
                autoclose: true,
                todayBtn: true,
                minView: 3,
                startView: vStartView,
                language: "zh-CN"
            });

            $("#txt_" + controlID).val(vTimeGlobal);
            $('#div_' + controlID).datetimepicker('setStartDate', vStartGlobal);
            if (endDay) {
                $('#div_' + controlID).datetimepicker('setEndDate', vEndGlobal);
            }
            //动态设置最小值
            vControlDate.on('changeDate', function (e) {
                if (e.date) {
                    vTimeGlobal = new Date(e.date.valueOf()).dateFormat(format);
                } else {
                    vTimeGlobal = new Date().dateFormat(format);
                }

                if (method && method != "") {
                    eval(method + " ();");
                }
            });

            if (method && method != "") {
                eval(method + " ();");
            }
        } catch (e) {
        }
    },
    now() {
        var datetime = new Date();

        var year = datetime.getFullYear();
        var month = datetime.getMonth() + 1 < 10 ? "0" + (datetime.getMonth() + 1) : datetime.getMonth() + 1;
        var date = datetime.getDate() < 10 ? "0" + datetime.getDate() : datetime.getDate();
        var hour = datetime.getHours() < 10 ? "0" + datetime.getHours() : datetime.getHours();
        var minute = datetime.getMinutes() < 10 ? "0" + datetime.getMinutes() : datetime.getMinutes();
        var second = datetime.getSeconds() < 10 ? "0" + datetime.getSeconds() : datetime.getSeconds();
        return year + "-" + month + "-" + date + " " + hour + ":" + minute + ":" + second;
    }
}

// 日期属性
Date.prototype.dateFormat = function (fmt) {
    var o = {
        //月份
        "M+": this.getMonth() + 1,
        //日  
        "d+": this.getDate(),
        //小时   
        "h+": this.getHours(),
        //分  
        "m+": this.getMinutes(),
        //秒  
        "s+": this.getSeconds(),
        //季度   
        "q+": Math.floor((this.getMonth() + 3) / 3),
        //毫秒  
        "S": this.getMilliseconds()
    };
    if (/(y+)/.test(fmt))
        fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
    for (var k in o)
        if (new RegExp("(" + k + ")").test(fmt))
            fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
    return fmt;
}

// 通用工具栏
const Common = {
    exitsFunction(funcName) {
        try {
            if (typeof (eval(funcName)) == "function") {
                return true;
            }
            else {
                return false;
            }
        } catch (e) {
            return false;
        }
    },
    getPrimaryKey(primaryKey, comparyKey, comparyValue, showKey, tableId) {

        var vRows = $("#" + tableId).bootstrapTable('getSelections');

        if (vRows.length > 0) {
            var vShowKeys = "";
            var vPrimaryKeys = "";

            for (var i = 0; i < vRows.length; i++) {
                var vValue = vRows[i][comparyKey];

                if (vValue.indexOf("</span>") > -1) {

                    vValue = vValue.substr(vValue.indexOf(">") + 1);
                    vValue = vValue.substr(0, vValue.indexOf("<"));
                }

                if (vValue == comparyValue) {
                    vShowKeys += vRows[i][showKey] + ",";
                    vPrimaryKeys += vRows[i][primaryKey] + ",";
                }
                else {
                    alert("[" + vRows[i][showKey] + "]状态不符,无法进行操作!");

                    return null;
                }
            }

            if (vPrimaryKeys.length > 0) {
                vPrimaryKeys = vPrimaryKeys.substr(0, vPrimaryKeys.length - 1);
            }

            if (vShowKeys.length > 0) {
                vShowKeys = vShowKeys.substr(0, vShowKeys.length - 1);
            }

            if (confirm("确定对[" + vShowKeys + "]进行操作?")) {

                return vPrimaryKeys;
            }
        }

        return null;
    },
    getSelectKey(primaryKey, tableId) {

        var vRows = $("#" + tableId).bootstrapTable('getSelections');

        if (vRows.length > 0) {
            var vShowKeys = "";
            var vPrimaryKeys = "";

            for (var i = 0; i < vRows.length; i++) {

                vPrimaryKeys += vRows[i][primaryKey] + ",";
            }

            if (vPrimaryKeys.length > 0) {
                vPrimaryKeys = vPrimaryKeys.substr(0, vPrimaryKeys.length - 1);
            }

            return vPrimaryKeys;
        }

        return null;
    },
    stringToBytes(str) {
        var array = new Uint8Array(str.length);
        for (var i = 0, l = str.length; i < l; i++) {
            array[i] = str.charCodeAt(i);
        }
        return array;
    }
}

// 查询列表类
function XheList() {

    var _model;
    var _BootstrapTable;

    var verifyUtil = new VerifyUtil();

    this.model = {
        Url: function () {
            return OPENAPIURL;
        },
        Methed: "Get_1_0",
        Filter: "",
        Value: "",
        TableID: "",
        ModalID: "",
        Title: "",
        SecondTitle: "",
        Connection: "",
        DBType: DBTYPE,
        Schema: "",
        Table: "",
        Join: [],
        Columns: "",
        Rows: 0,
        Page: 1,
        SortOrder: "asc",
        GroupName: "",
        SortName: "ID",
        UniqueID: "ID",
        PrimaryKey: "",
        Result: [],
        PageSize: function () {

            var clientWidth = window.screen.width;
            var clientHeight = window.screen.height;
            var documentHeight = $(document).height();
            var windowHeight = $(window).height();

            //alert("clientHeight:" + clientHeight + ",documentHeight:" + documentHeight + ",windowHeight:" + windowHeight);

            if (clientHeight > 1050 && clientHeight <= 1080) {
                return 12;
            }
            else if (clientHeight > 1024 && clientHeight <= 1050) {
                return 11;
            }
            else if (clientHeight > 990 && clientHeight <= 1024) {
                return 11;
            }
            else if (clientHeight > 900 && clientHeight <= 990) {
                return 10;
            }
            else if (clientHeight > 800 && clientHeight <= 900) {
                return 8;
            }
            else if (clientHeight > 768 && clientHeight <= 800) {
                return 5;
            }
            else if (clientHeight > 720 && clientHeight <= 768) {
                return 5;
            }
            else if (clientHeight > 600 && clientHeight <= 720) {
                return 5;
            }
            else if (clientHeight <= 600) {
                return 5;
            }
            else {
                return 12;
            }
        },
        IsMutilColumn: false,
        IsModal: false,
        IsPage: true,
        IsExport: false,
        Event: null,
        Checked: true,
        ClassName: "form-control",
        Number: false,
        Total: false,
        Token: TOKEN,
        UserName: "",
        RealName: "",
        Button: {
            Show: "",
            Edit: "",
            Info: "",
            Delete: "",
            Apply: "",
            Approval: ""
        }
    };

    this.search = function () {

        try {
            XheList._model = this.model;
            this.model.Event = clickEvent;

            if (Object.keys(this.model.Filter).length > 0) {
                var vFilter = Control.search("form-control");

                for (var i = 0; i < vFilter.length; i++) {
                    this.model.Filter.push(vFilter[i]);
                }
            }
            else {
                this.model.Filter = Control.search("form-control");
            }

            var vJudgeResult = verifyUtil.judgeSpecialText(this.model.Filter, 4);

            if (vJudgeResult == "") {

                //动态获取表头
                var aryColTitles = [];
                var aryHiddenColumns = [];

                if (this.model.Checked) {
                    var vCol = new Object();
                    vCol.field = this.model.UniqueID;
                    vCol.title = "";
                    vCol.width = "3%";
                    vCol.align = "center";
                    vCol.valign = "middle";
                    vCol.checkbox = true;
                    vCol.formatter = checkedEvent;

                    aryColTitles.push(vCol);
                }

                if (this.model.Number) {
                    var vCol = new Object();
                    vCol.field = "Number";
                    vCol.title = "序号";
                    vCol.width = "4%";
                    vCol.align = "center";
                    vCol.valign = "middle";
                    vCol.formatter = numberEvent;

                    aryColTitles.push(vCol);
                }

                for (var i = 0; i < this.model.Columns.length; i++) {

                    var vCol = new Object();
                    vCol.field = this.model.Columns[i][0];
                    vCol.title = this.model.Columns[i][1];
                    vCol.width = this.model.Columns[i][2] + "%";
                    vCol.valign = "middle";

                    if (this.model.Columns[i][5] != "") {

                        vCol.formatter = formatEvent;
                    }

                    if (vCol.title == "") {
                        vCol.visible = false;
                    }

                    if (this.model.Columns[i][3] == "null") {

                        vCol.formatter = this.model.Event;
                        vCol.align = "center";
                    }
                    else {
                        if (this.model.Columns[i][3]) {
                            vCol.align = this.model.Columns[i][3];
                        }
                        else {
                            vCol.align = "center";
                        }
                    }

                    aryColTitles.push(vCol);


                    if (this.model.Columns[i][2] == "0") {
                        aryHiddenColumns.push(vCol.field);
                    }
                }

                var Columns = [];
                if (this.model.IsMutilColumn) {
                    Columns.push(aryColTitles[0]);
                    Columns.push(aryColTitles[1]);
                } else {
                    Columns.push(aryColTitles);
                }

                var vBootstrapTable = {
                    url: this.model.Url(),
                    method: 'POST',
                    //contentType: "application/x-www-form-urlencoded; charset=utf-8",
                    contentType: "text/plain;charset=utf-8",
                    dataType: "json",
                    ajaxOptions: {
                        headers: getHeader()
                    },
                    //toolbar: '#toolbar',                //工具按钮用哪个容器
                    striped: true,                      //是否显示行间隔色
                    cache: false,                       //是否使用缓存，默认为true，所以一般情况下需要设置一下这个属性（*）
                    pagination: this.model.IsPage,                   //是否显示分页（*）
                    sortable: true,                     //是否启用排序
                    sortOrder: this.model.SortOrder,                   //排序方式
                    //queryParams: 'queryParams',         //传递参数（*）
                    sidePagination: "server",           //分页方式：client客户端分页，server服务端分页（*）
                    pageNumber: 1,                       //初始化加载第一页，默认第一页
                    pageSize: this.model.PageSize(),                       //每页的记录行数（*）
                    pageList: [10, 15, 25, 30, 50, 70, 100, 150, 200],        //可供选择的每页的行数（*）
                    smartDisplay: false,
                    locale: "zh-CN",
                    search: false,                      //是否显示表格搜索，此搜索是客户端搜索，不会进服务端，所以，个人感觉意义不大
                    strictSearch: true,
                    showColumns: false,                 //是否显示所有的列
                    showRefresh: false,                 //是否显示刷新按钮
                    minimumCountColumns: 2,             //最少允许的列数
                    clickToSelect: true,                //是否启用点击选中行
                    //height: 500,                        //行高，如果没有设置height属性，表格自动根据记录条数觉得表格高度                        
                    sortName: this.model.SortName,                     //排序字段
                    uniqueId: "",//SearchModel.UniqueID,                     //每一行的唯一标识，一般为主键列
                    showToggle: false,                   //是否显示详细视图和列表视图的切换按钮
                    cardView: false,                    //是否显示详细视图
                    detailView: false,                   //是否显示父子表
                    showExport: this.model.IsExport,
                    buttonsAlign: "right",
                    exportTypes: ['xlsx'],
                    exportDataType: "all",
                    exportOptions: {
                        fileName: this.model.Title,  //文件名称设置
                        worksheetName: this.model.Title,  //表格工作区名称
                        tableName: this.model.Title
                    },
                    modal: this.model,
                    columns: aryColTitles,
                    result: [],
                    //得到查询的参数
                    queryParams: function (params) {
                        var vPageIndex = (params.offset / params.limit) + 1;
                        var vParams = "";
                        //页面大小
                        vParams += "\"Rows\":" + params.limit + ",";
                        //页码                       
                        vParams += "\"Page\":" + vPageIndex + ",";
                        //排序列名   
                        vParams += "\"SortName\":\"" + params.sort + "\",";
                        //排位命令（desc，asc）                      
                        vParams += "\"SortOrder\":\"" + params.order + "\"";

                        var aryColumns = new Array();

                        for (let i = 0; i < this.modal.Columns.length; i++) {

                            aryColumns.push(Object.assign([], this.modal.Columns[i]));

                            //aryColumns[i][5] = "";
                        }

                        //alert(JSON.stringify(aryColumns));

                        var vRequest = GZip.zip("{\"Method\":\"" + this.modal.Methed + "\",\"Token\":\"" + this.modal.Token + "\",\"LoginName\":\"" + this.modal.UserName + "\",\"UserName\":\"" + this.modal.RealName + "\",\"DBType\":\"" + this.modal.DBType + "\",\"Params\":{\"Table\":\"" + (this.modal.DBType.toLowerCase().indexOf("gauss") > -1 ? this.modal.Schema + "." + this.modal.Table : this.modal.Table) + "\",\"Columns\":" + JSON.stringify(aryColumns) + ",\"Join\":" + JSON.stringify(this.modal.Join) + ",\"Filter\":" + JSON.stringify(this.modal.Filter) + ",\"Value\":" + JSON.stringify(this.modal.Value) + ",\"GroupName\":\"" + this.modal.GroupName + "\"," + vParams + "}}");


                        //console.log(XheList._model);
                        //console.log(this.modal);

                        //return encodeURI(vRequest);

                        return encodeURIComponent(vRequest);
                    },
                    onLoadSuccess: function (data) {

                        //alert(JSON.stringify(data))

                        data = JSON.parse(GZip.unzip(data[0]));

                        this.result = data;

                        $("#" + this.modal.TableID).bootstrapTable("load", data)
                    },
                    onLoadError: function (e, m) {
                        alert("error:" + JSON.stringify(e));
                        alert("msg:" + JSON.stringify(m));
                        //backLogin();
                    },
                    onClickCell: function (field, value, row, element) {

                        //CellClickEvent(field, value, row, element);
                    },
                    //隔行变色
                    rowStyle: function (row, index) {

                        var classesArr = ['os', 'js'];
                        if (this.modal.IsModal) {
                            classesArr = ['success', 'active'];
                        }
                        var strclass = "";
                        if (index % 2 == 0) {
                            //偶数行
                            strclass = classesArr[0];
                        } else {
                            //奇数行
                            strclass = classesArr[1];
                        }

                        return { classes: strclass };
                    }
                };


                var dataTable = $("#" + this.model.TableID).bootstrapTable('destroy').bootstrapTable(vBootstrapTable);

                if (aryHiddenColumns.length > 0) {
                    for (var i = 0; i < aryHiddenColumns.length; i++) {
                        $("#" + this.model.TableID).bootstrapTable('hideColumn', aryHiddenColumns[i]);
                    }
                }


            }
            else {
                alert("查询条件中包含敏感字: " + vJudgeResult + " ,请重新输入!");
            }

        } catch (e) {
            alert("查询出错:" + e);
        }
    };

    this.query = function () {

        let vResult = "";

        try {
            //请求接口
            vResult = HttpUtil.doPost(this.model);
        }
        catch (e) {
            alert(e)
        }

        return vResult;
    };

    this.show = function (model, value, row, index) {
        try {

            if (Common.exitsFunction("show")) {
                show(model, value, row, index);
            }
            else {


                if (row != undefined) {


                    Control.clear(model.ClassName);

                    //编辑模式
                    var vPrimaryValue = row[model.PrimaryKey];

                    model.Filter = [
                        [model.PrimaryKey, "A", "EQ", "C", vPrimaryValue]
                    ];

                    $("#txt_PK_Value").val(vPrimaryValue);

                    this.operate("get", model);

                    //显示编辑层
                    $('#' + model.ModalID).modal('show');
                }
                else {

                    Control.clear(this.model.ClassName);

                    //添加模式
                    $("#txt_PK_Value").val("");

                    //显示编辑层
                    $('#' + this.model.ModalID).modal('show');
                }


            }
        } catch (e) {
            alert(e);
        }
    }

    this.add = function () {
        try {
            $("#txt_PK_Value").val("");

            this.model.Filter = [];

            this.operate("add", this.model);

        } catch (e) {
            alert(e);
        }
    };

    this.edit = function () {
        try {

            if ($("#txt_PK_Value").val() == "") {

                this.add();
            }
            else {
                let vPrimaryValue = $("#txt_PK_Value").val();

                this.model.Filter = [
                    [this.model.PrimaryKey, "A", "EQ", "C", vPrimaryValue]
                ];

                this.operate("edit", this.model);
            }

        } catch (e) {
            alert(e);
        }
    };

    this.info = function (model, value, row, index) {
        try {
            if (Common.exitsFunction("info")) {
                info(model, value, row, index);
            }
            else {
                Control.clear(model.ClassName);
                //显示编辑层
                $('#' + model.ModalID).modal('show');
            }
        } catch (e) {
            alert(e);
        }
    };

    this.del = function () {
        try {
            if (Common.exitsFunction("delete")) {
                delete (value, row, index);
            }
            else {
                Control.clear(this.model.ClassName);
                //显示编辑层
                $('#' + this.model.ModalID).modal('show');
            }
        } catch (e) {
            alert(e);
        }
    };

    this.apply = function () {
        try {
            if (Common.exitsFunction("apply")) {
                apply(value, row, index);
            }
            else {
                Control.clear(this.model.ClassName);
                //显示编辑层
                $('#' + this.model.ModalID).modal('show');
            }
        } catch (e) {
            alert(e);
        }
    };

    this.approval = function () {
        try {
            if (Common.exitsFunction("approval")) {
                approval(value, row, index);
            }
            else {
                clearControls(this.model.ClassName);
                //显示编辑层
                $('#' + this.model.ModalID).modal('show');
            }
        } catch (e) {
            alert(e);
        }
    };

    function clickEvent(value, row, index) {

        let buttonHtml = "";
        try {

            let vRow = JSON.stringify(row).replace(/\"/g, "'");
            let vModel = JSON.stringify(XheList._model).replace(/\"/g, "'");

            if (XheList._model.Button.Show != "") {
                buttonHtml += "<button class=\"btn btn-info btn-sm power-search\" onclick=\"new XheList().show(" + vModel + ",'" + value + "'," + vRow + "," + index + ")\"> " + XheList._model.Button.Show + " </button> ";
            }
            if (XheList._model.Button.Info != "") {
                buttonHtml += "<button class=\"btn btn-warning btn-sm power-search\" onclick=\"new XheList().info(" + vModel + ",'" + value + "'," + vRow + "," + index + ")\"> " + XheList._model.Button.Info + " </button> ";
            }
            if (XheList._model.Button.Delete != "") {
                buttonHtml += "<button class=\"btn btn-danger btn-sm power-search\" onclick=\"new XheList().delete(" + vModel + ",'" + value + "'," + vRow + "," + index + ")\"> " + XheList._model.Button.Delete + " </button> ";
            }
            if (XheList._model.Button.Apply != "") {
                buttonHtml += "<button class=\"btn btn-success btn-sm power-search\" onclick=\"new XheList().apply(" + vModel + ",'" + value + "'," + vRow + "," + index + ")\"> " + XheList._model.Button.Apply + " </button> ";
            }
            if (XheList._model.Button.Approval != "") {
                buttonHtml += "<button class=\"btn btn-primary btn-sm power-search\" onclick=\"new XheList().approval(" + vModel + ",'" + value + "'," + vRow + "," + index + ")\"> " + XheList._model.Button.Approval + " </button> ";
            }
        }
        catch (e) {
            alert(e);
        }
        return buttonHtml;
    };

    function checkedEvent(row, index) { };

    function numberEvent(value, row, index) {
        //获取每页显示的数量
        var pageSize = $('#' + XheList._model.TableID).bootstrapTable('getOptions').pageSize;
        //获取当前是第几页
        var pageNumber = $('#' + XheList._model.TableID).bootstrapTable('getOptions').pageNumber;
        //返回序号，注意index是从0开始的，所以要加上1
        return pageSize * (pageNumber - 1) + index + 1;
    };

    function formatEvent(value, row, index, col) {

        for (let i = 0; i < XheList._model.Columns.length; i++) {
            if (XheList._model.Columns[i][0] == col) {

                for (let j = 0; j < XheList._model.Columns[i][5].length; j++) {
                    if (XheList._model.Columns[i][5][j]["key"] == value) {
                        return XheList._model.Columns[i][5][j]["value"];
                    }
                }

                break;
            }
        }

        //alert(JSON.stringify(row));
        //alert(e);
    };

    this.getJoinModel = function () {
        var _Option = {
            Table: "",
            Union: "left",
            Filter: []
        }
        return _Option;
    };

    this.operate = function (type, model) {

        var vModel = new XheList().model;
        vModel.Schema = model.Schema;
        vModel.Table = model.Table;
        vModel.UniqueID = model.UniqueID;
        vModel.SortName = model.SortName;
        vModel.Filter = model.Filter;
        vModel.Columns = Control.get(model.ClassName);

        switch (type) {
            case "get":
                vType = "查询";
                vModel.Methed = "Get_1_0";
                break;
            case "edit":
                vType = "编辑";
                vModel.Methed = "Edit_1_0";
                break;
            case "add":
                vType = "添加";
                vModel.Methed = "Add_1_0";
                break;
            case "approval":
                vType = "审批";
                vModel.Methed = "Edit_1_0";
                vModel.Columns = searchModel.Columns;
                break;
        }

        var vJudgeResult = "";
        var vMessage = "";

        if (type == "get") {
            vJudgeResult = verifyUtil.judgeSpecialText(vModel.Columns, 4);
            vMessage = "查询条件中包含敏感字: " + vJudgeResult + " ,请重新输入!"
        }
        else {

            vJudgeResult = verifyUtil.judgeSpecialText(vModel.Columns, 1);
            vMessage = "输入字符中包含敏感字: " + vJudgeResult + " ,请重新输入!"
        }

        if (vJudgeResult != "") {

            alert(vMessage);
            return;
        }

        try {

            if (verifyUtil.verifyAll(type, model.ClassName) == true) {

                //alert(JSON.stringify(vModel));

                //请求接口
                var vResult = HttpUtil.doPost(vModel);

                if (type == "get") {
                    //绑定数据
                    Control.bind(model.ClassName, vResult.rows);

                    //显示编辑层
                    //$('#' + model.ModalID).modal('show');
                }
                else {
                    //alert(JSON.stringify(vResult.result))

                    //返回结果
                    if (vResult.result) {
                        //alert(vType + "成功!");
                        alert("操作成功!");

                        //重新查询数据
                        if (Common.exitsFunction("search")) {
                            search();
                        }

                        //隐藏编辑层
                        $('#' + model.ModalID).modal('hide');
                    }
                    else {
                        //alert(vType + "失败:" + vResult.message);
                        alert("操作失败:" + vResult.message);
                    }
                }
            }
        } catch (e) {
            //alert(vType + "失败:" + e);
            alert("操作成功:" + e);
        }
    };
}

// 多维列表类
const MultiTable = {
    bindTable(id, columns, rows, total) {
        try {
            var vHtml = '<table cellpadding="0" cellspacing="0" class="tbl-data">';

            var vTitleRowCount = getTitleRowCount(columns);

            for (var i = 0; i < vTitleRowCount; i++) {
                vHtml += getTableTitle(columns, i, vTitleRowCount);
            }

            var vTotal = {};
            for (var i = 0; i < columns.length; i++) {

                var vTitle = columns[i][1];
                var vWidth = columns[i][2];
                var vDataType = columns[i][4];

                if (vWidth != "0") {

                    if (vDataType == "I" || vDataType == "F") {
                        vTotal[vTitle] = 0;
                    }
                    else {
                        if (i == 0) {
                            vTotal[vTitle] = "合计";
                        }
                        else {
                            vTotal[vTitle] = "-";
                        }
                    }
                }
            }


            var vClass = ['tr-os', 'tr-js'];

            for (var i = 0; i < rows.length; i++) {

                vHtml += '<tr class="' + vClass[i % 2] + '" onmouseover="this.style.background=\'#455469\'" onmouseout="this.style.background=\'\'">';

                for (var j = 0; j < columns.length; j++) {

                    if (columns[j][2] != "0") {
                        var vKey = columns[j][1];
                        var vEvent = false;

                        if (columns[j][5].indexOf("event:true") > -1) {
                            vEvent = true;
                        }

                        vHtml += '<td class="td-main">' + (vEvent ? "<a href='#' onclick='rowEvent(\"" + String(rows[i][vKey]) + "\"," + JSON.stringify(rows[i]) + "," + i + "," + j + ")'>" + rows[i][vKey] + "</a>" : rows[i][vKey]) + '</td>';


                        //计算合计
                        if (columns[j][4] == "I" || columns[j][4] == "F") {

                            vTotal[vKey] = vTotal[vKey] + rows[i][vKey];
                        }
                    }
                }

                vHtml += '</tr>';
            }

            if (total) {
                vHtml += '<tr class="tr-ds">';

                for (var i = 0; i < columns.length; i++) {

                    if (columns[i][2] != "0") {

                        vHtml += '<td class="td-title" style="width:' + columns[i][2] + '%">' + vTotal[columns[i][1]] + '</td>';
                    }
                }

                vHtml += '</tr>';
            }

            vHtml += '</table>';

            document.getElementById(id).innerHTML = vHtml;

        } catch (e) {
            alert(e);
        }
    },
    getTitleRowCount(columns) {
        var vTitleRowCount = 1;

        for (var i = 0; i < columns.length; i++) {

            var vTitle = columns[i][1];
            var vWidth = columns[i][2];
            var vDataType = columns[i][4];

            if (vWidth != "0") {

                if (vTitle.indexOf("$$") > -1) {

                    var vLength = vTitle.split("$$").length;

                    if (vLength > vTitleRowCount) {
                        vTitleRowCount = vLength;
                    }
                }
            }
        }

        return vTitleRowCount;
    },
    getTableTitle(columns, rowIndex, rowCount) {
        var vHtml = '<tr class="tr-ds">';

        var vConSpan = 1;

        for (var i = 0; i < columns.length; i++) {

            var vTitle = columns[i][1];
            var vWidth = columns[i][2];
            var vDataType = columns[i][4];

            if (vWidth != "0") {

                if (rowCount > 1) {
                    //多级表头
                    if (i == 0) {
                        if (rowIndex == 0) {
                            vHtml += '<td class="td-title" style="width:' + vWidth + '%" rowspan="' + rowCount + '">' + vTitle + '</td>';
                        }
                    }
                    else {
                        var vBorderClass = "";

                        if (rowIndex > 0) {
                            vBorderClass = "td-top-border";
                        }

                        var aryTitles = vTitle.split("$$");

                        if (vConSpan > 1) { }
                        else {
                            vHtml += '<td class="td-title ' + vBorderClass + '" colspan="{&&&}" style="width:' + vWidth + '%">' + aryTitles[rowIndex] + '</td>';
                        }

                        if (columns[i + 1] != undefined) {

                            var aryNextTitle = columns[i + 1][1].split("$$");



                            if (aryTitles[rowIndex] == aryNextTitle[rowIndex]) {

                                vConSpan += 1;
                            }
                            else {

                                vHtml = vHtml.replace("{&&&}", vConSpan);
                                vConSpan = 1;
                            }
                        }
                        else {
                            vHtml = vHtml.replace("{&&&}", vConSpan);
                            vConSpan = 1;
                        }
                    }
                }
                else {
                    //单行表头
                    vHtml += '<td class="td-title" style="width:' + vWidth + '%">' + vTitle + '</td>';

                }
            }
        }

        vHtml = vHtml.replace("{&&&}", 1);

        vHtml += '</tr>';

        return vHtml;
    },
    rowEvent(value, row, index, number) {
        alert(value)
        event(value, row, index, number)
    }
}

// 控件操作类
const Control = {
    // 遍历指定域内的控件，获得查询条件
    get(className) {
        var vColumns = new Array();

        var vPanel = document.getElementsByClassName(className);

        for (var i = 0; i < vPanel.length; i++) {

            try {
                //控件ID
                var vControlID = vPanel[i].id;

                if (vControlID.split("_").length == 2) {

                    //Key
                    var vKey = vControlID.split("_")[1];

                    if (vKey != undefined && vKey != "") {

                        //控件值
                        var vValue = "";
                        var vBind = true;
                        var vFormat = "";
                        var vDefaultValue = "";
                        var vDataType = "C";
                        var vMatch = false;

                        if (vPanel[i].attributes["class"].value.indexOf("selectpicker") > -1) {

                            vValue = $('#' + vControlID).selectpicker('val')
                        }
                        else {
                            vValue = $('#' + vControlID).val();
                        }

                        //数据类型
                        if (vPanel[i].attributes["datatype"] != undefined) {
                            vDataType = vPanel[i].attributes["datatype"].value;
                        }

                        //格式化结果
                        if (vPanel[i].attributes["format"] != undefined) {
                            vFormat = vPanel[i].attributes["format"].value;
                        }

                        //格式化结果
                        if (vPanel[i].attributes["defaultvalue"] != undefined) {
                            if (vPanel[i].attributes["defaultvalue"].value == "sysdate") {
                                vValue = getTimeNow("yyyy-mm-dd hh:mm:ss");
                            }
                            else {
                                vDefaultValue = vPanel[i].attributes["defaultvalue"].value;
                            }
                        }

                        //是否绑定
                        if (vPanel[i].attributes["bind"] != undefined && vPanel[i].attributes["bind"].value == "false") {
                            vBind = false;
                        }

                        var vColumn = [vKey, vValue, "", vDefaultValue, vDataType, vFormat, vBind];
                        vColumns.push(vColumn);
                    }
                }
            } catch (e) {
                alert(e);
            }
        }

        return vColumns;
    },
    // 清理指定域内的控件
    clear(className) {

        var vPanel = document.getElementsByClassName(className);

        for (var i = 0; i < vPanel.length; i++) {
            try {

                //控件ID
                var vControlID = vPanel[i].id;

                if (vControlID.split("_").length == 2) {

                    var vType = vControlID.split("_")[0];
                    //Key
                    var vKey = vControlID.split("_")[1];

                    if (vKey != undefined && vKey != "") {

                        //控件值
                        var vControl = document.getElementById(vControlID);

                        if (vControl.attributes["clear"] != undefined && vControl.attributes["clear"].value == "false") {
                            continue;
                        }

                        if (vControl.attributes["edited"] != undefined) {

                            $("#" + vControlID).attr("disabled", false);
                        }

                        if (vType == "txt") {

                            //绑定值
                            if (vPanel[i].attributes["onbind"] != undefined) {
                                document.getElementById(vControlID).value = eval(vPanel[i].attributes["onbind"].value);
                            }
                            else {
                                //控件值
                                document.getElementById(vControlID).value = "";
                            }
                        }
                        else if (vType == "ddl") {

                            var vMatched = false;

                            for (var j = 0; j < vControl.options.length; j++) {

                                if (vControl.options[j].attributes["defaulted"] != undefined && vControl.options[j].attributes["defaulted"].value) {

                                    if (vControl.attributes["class"].value.indexOf("selectpicker") > -1) {

                                        $('#' + vControlID).selectpicker('val', vControl.options[j].value);
                                    }
                                    else {
                                        vControl.value = vControl.options[j].value;
                                    }

                                    vMatched = true;
                                    break;
                                }
                            }

                            if (!vMatched) {
                                if (vControl.attributes["class"].value.indexOf("selectpicker") > -1) {

                                    $('#' + vControlID).selectpicker('val', "");
                                }
                                else {
                                    vControl.value = "";
                                }
                            }
                        }
                    }
                }
            } catch (e) {
                alert(e);
            }
        }
    },
    // 遍历指定域内的控件，获得查询条件
    search(className) {
        var vColumns = new Array();

        var vPanel = document.getElementsByClassName(className);

        for (var i = 0; i < vPanel.length; i++) {
            try {
                //控件ID
                var vControlID = vPanel[i].id;

                if (vControlID.split("_").length >= 3 && vControlID != "txt_PK_Value") {

                    //Key
                    var vKey = vControlID.split("_")[2];

                    if (vKey != undefined && vKey != "") {

                        //控件值
                        var vValue = $('#' + vControlID).val();
                        var vUnion = "";
                        var vExist = "";
                        var vDataType = "C";
                        var vMatch = false;
                        var vAlias = "";

                        //数据类型
                        if (vPanel[i].attributes["union"] != undefined) {
                            vUnion = vPanel[i].attributes["union"].value;
                        }

                        //查询类型
                        if (vPanel[i].attributes["exist"] != undefined) {
                            vExist = vPanel[i].attributes["exist"].value;
                        }

                        //格式化结果
                        if (vPanel[i].attributes["datatype"] != undefined) {
                            vDataType = vPanel[i].attributes["datatype"].value;
                        }

                        //查询类型
                        if (vPanel[i].attributes["alias"] != undefined) {
                            if (vPanel[i].attributes["alias"].value != "") {
                                vKey = vPanel[i].attributes["alias"].value + "." + vKey;
                            }
                        }

                        vColumns.push([vKey, vUnion, vExist, vDataType, vValue]);
                    }
                }
            } catch (e) {
                //alert(e);
            }
        }

        return vColumns;
    },
    // 绑定数据
    bind(className, value) {

        var vPanel = document.getElementsByClassName(className);

        for (var i = 0; i < vPanel.length; i++) {
            try {
                var vControlID = vPanel[i].id;

                if (vControlID.split("_").length == 2) {

                    var vKey = vControlID.split("_")[1];

                    if (vKey != undefined && vKey != "") {

                        if (document.getElementById(vControlID).attributes["class"].value.indexOf("selectpicker") > -1) {
                            if (document.getElementById(vControlID).attributes["onbind"] != undefined) {

                                if (vPanel[i].attributes["onbind"].value.indexOf("()") > -1) {
                                    eval(vPanel[i].attributes["onbind"].value.replace("(", "(" + JSON.stringify(value[0][vKey])));
                                }
                                else {

                                    eval(vPanel[i].attributes["onbind"].value.replace(")", "," + JSON.stringify(value[0][vKey]) + ")"));
                                }
                            }
                            else {
                                //OptionUtil.bind(id, key, value, result, disabled, checkedValue, defaultValue, format) 

                                $('#' + vControlID).selectpicker('val', value[0][vKey]);
                            }
                            //$('#' + vControlID).attr("defaultValue", value[0][vKey]);
                            //$('#' + vControlID).attr("checkedValue", JSON.stringify(value[0][vKey]));
                        }
                        else {

                            if (vControlID.indexOf("spn_") > -1) {
                                document.getElementById(vControlID).innerHTML = value[0][vKey];
                            }
                            else {
                                if (document.getElementById(vControlID).attributes["binded"] != undefined) {

                                    eval(vPanel[i].attributes["binded"].value.replace("(", "(" + JSON.stringify(value[0][vKey])));
                                }
                                else if (document.getElementById(vControlID).attributes["format"] != undefined) {
                                    if (document.getElementById(vControlID).attributes["format"].value.indexOf("()") > -1) {
                                        document.getElementById(vControlID).value = eval(vPanel[i].attributes["format"].value.replace("(", "(" + JSON.stringify(value[0][vKey])));
                                    }
                                    else {

                                    }
                                }
                                else {
                                    document.getElementById(vControlID).value = value[0][vKey];
                                }
                            }
                        }

                        if (document.getElementById(vControlID).attributes["edited"] != undefined) {

                            $("#" + vControlID).attr("disabled", document.getElementById(vControlID).attributes["edited"].value);
                        }
                    }
                }
            }
            catch (e) { }
        }
    }
}

// 验证类
function VerifyUtil() {
    //
    this.verifyMethod = [
        "verifyEmpty",
        "verifyNumber",
        "verifyDecimal",
        "verifyChinese",
        "verifyEnglish",
        "verifyCurrent",
        "verifyTelephone",
        "verifyEmail",
        "verifyIP",
        "verifyDate"
    ];
    //
    this.verifyAll = function (type, className) {
        if (type == "add") {
            type = "edit";
        }

        if (className != undefined) {
            className = className + "-";
        }
        else {
            className = "";
        }

        var vResult = true;

        for (var i = 0; i < this.verifyMethod.length; i++) {

            vResult = eval(this.verifyMethod[i] + "(\"" + type + "\",\"" + className + "\")");

            if (vResult == false) {
                break;
            }
        }

        return vResult;
    };
    //是否为空
    function verifyEmpty(type, className) {

        return verifyEvent(className + "verify-" + type + "-empty", /\S/, "不能为空!");

    };
    //是否是数字
    function verifyNumber(type, className) {

        return verifyEvent(className + "verify-" + type + "-number", /^\d+$/, "必须为数字!");
    };
    //是否带有小数
    function verifyDecimal(type, className) {

        return verifyEvent(className + "verify-" + type + "-decimal", /^\d+\.\d+$/, "必须为小数!");
    };
    //校验是否中文名称组成
    function verifyChinese(type, className) {

        return verifyEvent(className + "verify-" + type + "-chi", /^[\u4E00-\u9FA5]+$/, "必须为中文!");
    };
    //校验是否英文名称组成
    function verifyEnglish(type, className) {

        return verifyEvent(className + "verify-" + type + "-eng", /^[A-Za-z]+$/, "必须为中文!");
    };
    //校验名称是否合法
    function verifyCurrent(type, className) {

        return verifyEvent(className + "verify-" + type + "-cur", /^[a-zA-Z][a-zA-Z0-9_]{4,15}$/, "名称不合法!");
    };
    //校验电话号码格式
    function verifyTelephone(type, className) {

        return verifyEvent(className + "verify-" + type + "-tel", /^((0\d{2,3}-\d{7,8})|(1[3584]\d{9}))$/, "电话号码格式不正确!");
    };
    //校验邮箱地址是否合法
    function verifyEmail(type, className) {

        return verifyEvent(className + "verify-" + type + "-email", /^\w+@[a-zA-Z0-9]{2,10}(?:\.[a-z]{2,4}){1,3}$/, "邮箱地址不正确!");
    };
    //校验IP地址是否合法
    function verifyIP(type, className) {

        return verifyEvent(className + "verify-" + type + "-ip", /^\d+\.\d+\.\d+\.\d+$/, "IP地址不正确!");
    };
    //校验日期是否合法
    function verifyDate(type, className) {

        return verifyEvent(className + "verify-" + type + "-date", /^\d{4}-\d{1,2}-\d{1,2}/, "日期格式不正确!");
    };
    //校验指定className控件的值
    function verifyEvent(className, regExp, message) {

        var vControls = document.getElementsByClassName(className);

        for (var i = 0; i < vControls.length; i++) {

            try {
                //控件ID
                var vControl = document.getElementById(vControls[i].id);

                if (regExp.test(vControl.value) == false) {

                    setTimeout(function () {

                        if (vControl.id.indexOf("ddl_") > -1) {



                        }
                        else {
                            document.getElementById(vControl.id).select();
                        }

                    }, 500);

                    var vTitle = getVerifyTitle(vControl.id);

                    alert(vTitle + message);

                    return false;
                }
            }
            catch (e) { }
        }

        return true;
    };
    //获取控件的Title
    function getVerifyTitle(id) {

        var vTitle = "";
        var vTitleID = id.replace("txt_", "vrf_").replace("ddl_", "vrf_");

        if (vTitleID.indexOf("vrf_") > -1) {

            var vTitleControl = document.getElementById(vTitleID);

            if (vTitleControl != undefined) {

                vTitle = vTitleControl.innerHTML;

                do {
                    vTitle = vTitle.replace("&nbsp;", "");

                } while (vTitle.indexOf("&nbsp;") > -1);

                vTitle = "[" + vTitle.replace(":", "").replace("：", "") + "]";
            }
        }

        return vTitle;
    };
    //
    this.judgeSpecialText = function (clounms, index) {

        try {
            for (var i = 0; i < clounms.length; i++) {
                if (clounms[i][index] != null) {
                    var vText = clounms[i][index];

                    if (vText.indexOf("'") > -1) {
                        return "'";
                    }
                    else if (vText.indexOf("<") > -1) {
                        return "<";
                    }
                    else if (vText.indexOf(">") > -1) {
                        return ">";
                    }
                    // else if (vText.indexOf("or") > -1) {
                    //     return "or";
                    // }
                    else if (vText.indexOf("alert") > -1) {
                        return "alert";
                    }
                    else if (vText.indexOf("script") > -1) {
                        return "script";
                    }
                    else if (vText.indexOf(";") > -1) {
                        return ";";
                    }
                }
            }
        }
        catch (e) {
            //alert(e)
        }
        return "";
    };
}

// 请求类
const HttpUtil = {
    doPost(model) {

        var vRequest = encodeURIComponent(GZip.zip("{\"Method\":\"" + model.Methed + "\",\"Token\":\"" + model.Token + "\",\"LoginName\":\"" + model.UserName + "\",\"UserName\":\"" + model.RealName + "\",\"DBType\":\"" + model.DBType + "\",\"Params\":{\"Table\":\"" + (model.DBType.toLowerCase().indexOf("gauss") > -1 ? model.Schema + "." + model.Table : model.Table) + "\",\"Columns\":" + JSON.stringify(model.Columns) + ",\"Join\":" + JSON.stringify(model.Join) + ",\"Filter\":" + JSON.stringify(model.Filter) + ",\"Value\":" + JSON.stringify(model.Value) + ",\"Rows\":" + model.Rows + ",\"Page\":" + model.Page + ",\"GroupName\":\"" + model.GroupName + "\",\"SortName\":\"" + model.SortName + "\",\"SortOrder\":\"" + model.SortOrder + "\"}}"));
        var vResult = "";
        try {
            jQuery.support.cors = true;

            $.ajax({
                url: model.Url(),
                data: vRequest,
                type: "POST",
                async: false,
                contentType: "text/plain;charset=utf-8",
                dataType: "json",
                headers: getHeader(),
                success: function (data) {
                    //alert("data:" + JSON.stringify(data));

                    vResult = JSON.parse(GZip.unzip(data[0]));

                    //vResult = data.rows;

                },
                error: function (error) {
                    alert("error:" + JSON.stringify(error));

                    if (String(error.responseText).indexOf("Methed") != -1) {
                        vResult = error.responseText.replace("\\", "");
                    }
                    $("#errorMsg").html(error.responseText);
                }
            });
        }
        catch (e) {
            alert("11111" + e)
        }
        return vResult;
    },
    //解析参数(同域)
    getUrlParams() {
        try {
            var params, index = 0;

            for (; index < opener.windowPool.length; index++) {
                if (opener.windowPool[index].window === window) {
                    params = opener.windowPool[index].parameter;
                    break;
                }
            }
            return params;
        }
        catch (e) {
            return null;
        }
    },
    //同域传参
    setUrlParams(url, params) {
        // 用于存储子页面的 window 对象及隐式传递的参数
        window.windowPool = [];
        // 新建窗口，url 为报表页面地址

        var newWin = window.open(url);

        window.windowPool.push({
            "window": newWin,
            "parameter": params
        });
    },
    //解析参数(get)
    getQueryString(name) {
        var reg = new RegExp('(^|&)' + name + '=([^&]*)(&|$)', 'i');

        var r = window.location.search.substr(1).match(reg);

        if (r != null) {
            return unescape(r[2]);
        } else {
            return null;
        }
    }
}

const OptionUtil = {
    bind(id, key, value, result, disabled, checkedValue, defaultValue, format) {

        if (disabled == undefined) {
            disabled = false;
        }

        if (defaultValue == undefined) {
            defaultValue = null;
        }

        if (format == undefined) {
            format = "";
        }

        var vOptions = this.set(key, value, result, defaultValue, format);

        var vControl = document.getElementById(id);

        document.getElementById(id).innerHTML = vOptions;

        //var vUrlParams = getUrlParams();

        if (checkedValue != undefined) {

            if (vControl.attributes["class"].value.indexOf("selectpicker") > -1) {

                if (checkedValue.indexOf("[") > -1 && checkedValue.indexOf("]") > -1) {

                    $('#' + id).selectpicker('val', JSON.parse(checkedValue));
                }
                else {
                    try {
                        var vItems = String(checkedValue).split(",");
                        var vValue = "";

                        for (var i = 0; i < vItems.length; i++) {
                            if (vItems[i].indexOf('"') > -1) {
                                vValue += vItems[i] + ",";
                            }
                            else {
                                vValue += '"' + vItems[i] + '",';
                            }
                        }

                        if (vValue.length > 0) {
                            vValue = vValue.substr(0, vValue.length - 1);
                        }

                        $('#' + id).selectpicker('val', JSON.parse("[" + vValue + "]"));
                    }
                    catch (e) {
                        alert(e)
                    }
                    //$('#' + id).selectpicker('val', checkedValue.replace(/"/g, ""));              
                }
            }
            else {
                $("#" + id).val(checkedValue);
            }
        }

        if (vControl.attributes["class"].value.indexOf("selectpicker") > -1) {
            $('#' + id).selectpicker('refresh');
        }

        $("#" + id).attr("disabled", disabled);




    },
    set(key, value, result, defaultValue, format) {

        var vOption = "";
        try {
            if (defaultValue != null) {
                vOption += "<option value=\"" + defaultValue + "\" defaulted=\"true\">请选择</option>";
            }

            for (var i = 0; i < result.length; i++) {

                var vShowValue = result[i][value];

                if (format != "") {
                    vShowValue = format.replace("{0}", result[i][key]).replace("{1}", result[i][value])
                }

                vOption += "<option value=\"" + result[i][key] + "\">" + vShowValue + "</option>";
            }
        }
        catch (e) { }

        return vOption;
    }
}

const GZip = {

    // 压缩
    compress(str) {
        var binaryString = pako.gzip(escape(str), { to: 'string' });
        return binaryString;
    },
    // 解压
    decompress(str) {
        let strData = str;
        // Convert binary string to character-number array
        let charData = strData.split('').map(function (x) { return x.charCodeAt(0); });
        // Turn number array into byte-array
        let binData = new Uint8Array(charData);
        // // unzip
        let array = pako.inflate(binData);

        strData = ''
        /**
         * String.fromCharCode.apply(null, array) 显示 Maximum call stack size exceeded
         * 超过最大调用堆栈大小
         * 
         */
        let chunk = 8 * 1024;
        let i;
        for (i = 0; i < array.length / chunk; i++) {
            strData += String.fromCharCode.apply(null, array.slice(i * chunk, (i + 1) * chunk));
        }
        strData += String.fromCharCode.apply(null, array.slice(i * chunk));

        // 将乱码的中文进行转换
        return unescape(strData);
    },
    // 压缩
    zip(str) {
        var binaryString = pako.gzip((str), { to: 'string' })
        return btoa(binaryString);
    },
    // 解压
    unzip(b64Data) {
        var strData = atob(b64Data)
        var charData = strData.split('').map(function (x) { return x.charCodeAt(0) })
        var binData = new Uint8Array(charData)
        var data = pako.inflate(binData)
        // 这次我们只是需要将代码转换到这一步，再调用下面的函数就可以了，对比上面少了两步
        return this.Utf8ArrayToStr(data);
        //  执行这步再调用函数将数据处理一次 就不会出现乱码的情况
    },
    Utf8ArrayToStr(array) {
        var out, i, len, c;
        var char2, char3;

        out = "";
        len = array.length;
        i = 0;
        while (i < len) {
            c = array[i++];
            switch (c >> 4) {
                case 0: case 1: case 2: case 3: case 4: case 5: case 6: case 7:
                    // 0xxxxxxx
                    out += String.fromCharCode(c);
                    break;
                case 12: case 13:
                    // 110x xxxx   10xx xxxx
                    char2 = array[i++];
                    out += String.fromCharCode(((c & 0x1F) << 6) | (char2 & 0x3F));
                    break;
                case 14:
                    // 1110 xxxx  10xx xxxx  10xx xxxx
                    char2 = array[i++];
                    char3 = array[i++];
                    out += String.fromCharCode(((c & 0x0F) << 12) |
                        ((char2 & 0x3F) << 6) |
                        ((char3 & 0x3F) << 0));
                    break;
            }
        }
        return out;
    }
}

const Cookie = {
    setJSONCookie(key, value) {
        try {
            var vValue = GZip.compress(JSON.stringify(value));

            $.cookie(key, vValue, { expires: 1, path: '/' });
        }
        catch (e) { }
    },
    getJSONCookie(key) {

        var vCookieValue = null;

        try {
            var vCookie = $.cookie(key);

            if (vCookie != undefined && vCookie != null && vCookie != "" && vCookie != "null" && vCookie != "undefined") {

                vCookieValue = JSON.parse(GZip.decompress(vCookie));
            }
        }
        catch (e) {
        }

        return vCookieValue;
    }
}